package com.yinhanshi.s3test.http;

import com.google.gson.Gson;
import com.yinhanshi.s3test.bean.UploadPieceResponse;

import java.util.Map;

import io.reactivex.Observable;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class ApiRetrofit extends BaseApiRetrofit {

    private MyApi myApiFile;
    private MyApi myApiUser;
    private MyApi myApiVip;
    private static ApiRetrofit mInstance = null;

    private ApiRetrofit() {
        super();
        myApiFile =
                new Retrofit.Builder().baseUrl(MyApi.BASE_URL).client(getClient()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(MyApi.class);
        myApiUser =
                new Retrofit.Builder().baseUrl(MyApi.BASE_URL_USER).client(getClient()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(MyApi.class);
        myApiVip =
                new Retrofit.Builder().baseUrl(MyApi.BASE_URL_03).client(getClient()).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build().create(MyApi.class);
    }

    public synchronized static ApiRetrofit getInstance() {
        if (mInstance == null) {
            if (mInstance == null) {
                mInstance = new ApiRetrofit();
            }
        }
        return mInstance;
    }

    /**
     * 获取安全令牌
     */
    public Observable<BaseResponseBean> getSignedUrl(String loginId, String password) {
        RequestBody responseBean =getRequestBody(loginId);
        return myApiUser.getSignUrl(responseBean);
    }


    /**
     * 下载文件
     * @param fileId
     * @param startIndex
     * @param endIndex
     * @return
     */
    public Call<ResponseBody> downloadFile(String fileId, long startIndex, long endIndex) {
        return myApiFile.downloadFile("identity", fileId, startIndex, endIndex);
    }

    /**
     * 上传普通文件
     *
     * @param headers
     * @param part
     * @return
     */
    public Observable<UploadPieceResponse> uploadFile(Map<String, String> headers, MultipartBody.Part part) {
        return myApiFile.uploadFile(headers, part);
    }

    /**
     * 将 obj 转化成 RequestBody，用于网络请求
     * @param obj
     * @return
     */
    private RequestBody getRequestBody(Object obj) {
        String json = new Gson().toJson(obj);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
        return body;
    }

}
